package com.hz.web.controller;

import com.alibaba.fastjson.JSON;
import com.hz.web.entity.Sheet;
import com.hz.web.service.SheetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by kaddddd on 2018/5/9 0009.
 */
@Controller
public class MainController {
    @Autowired
    SheetService sheetService;

    @GetMapping("/")
    public String home1() {
        return "home";
    }

    @GetMapping("/home")
    public String home() {
        return "home";
    }

    @GetMapping("/admin")
    public String admin() {
        return "admin";
    }

    @GetMapping("/user")
    public String user(ModelMap model) {
        model.addAttribute("user", getPrincipal());
        return "user";
    }

    @GetMapping("/checker")
    public String checker(int status, ModelMap model) {
        model.addAttribute("checker", getPrincipal());
        List<Sheet> sheetList = sheetService.getSheetList(status);
        model.addAttribute("sheetList", sheetList);
        return "checker";
    }

    @GetMapping("/about")
    public String about() {
        return "about";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/widget")
    public String widget() {
        return "widget";
    }

    @GetMapping("/403")
    public String error403() {
        return "/error/403";
    }

    private String getPrincipal(){
        String userName = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            userName = ((UserDetails)principal).getUsername();
        } else {
            userName = principal.toString();
        }
        return userName;
    }

}
